package com.cloud.rou.im.cluster.naming.node;


import lombok.Data;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-11-08 20:50
 */
@Data
public class ImServerInstance implements Comparable<ImServerInstance> {
    //worker 的Id,ZooKeeper负责生成
    private long id;
    //Netty服务的连接数
    private AtomicInteger balance = new AtomicInteger(0) ;
    //Netty服务 IP
    private String host;
    //Netty服务端口
    private String port;
    public ImServerInstance(String host, String port, AtomicInteger balance, long id) {
        this.host = host;
        this.port = port;
        this.balance=balance;
        this.id= id;
    }
    public ImServerInstance(String host, String port) {
        this.host = host;
        this.port = port;
    }

    public ImServerInstance(Long id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "ImServerInstance{" +
                "id='" + id + '\'' +
                "host='" + host + '\'' +
                ", port='" + port + '\'' +
                ",balance=" + balance +
                '}';
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ImServerInstance node = (ImServerInstance) o;
        return id == node.id && Objects.equals(host, node.host) &&
                Objects.equals(port, node.port);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id, host, port);
    }
    /**
     * 用来按照负载升序排列
     */
    @Override
    public int compareTo(ImServerInstance o) {
        int weight1 = this.getBalance().get();
        int weight2 = o.getBalance().get();
        if (weight1 > weight2) {
            return 1;
        } else if (weight1 < weight2) {
            return -1;
        }
        return 0;
    }
}

